import type { App } from "vue";

import {
    createRouter,
    createWebHistory,
    createWebHashHistory,
    RouteRecordRaw,
} from "vue-router";
import { umsAdmin } from "../request/http";

import { useAdminStoreWithOut } from "../store/modules/admin";

const adminStore = useAdminStoreWithOut();

const routes:RouteRecordRaw[] = [
    {
        path:"/login",
        name:"login",
        component:()=>import("../pages/login/index.vue"),
    },
];

const router = createRouter({
    history:createWebHashHistory(),
    routes,
})

// 前置导航守卫
router.beforeEach(async (to,from,next)=>{
    const token = localStorage.getItem("token");

    if(token && adminStore.menus.length === 0){
        //获取用户信息
        const adminData = await umsAdmin.getAdminInfo();
        if(adminData.code === 200){
            adminStore.updateMenus(adminData.data.menus);
            // 生成动态路由规则
            const newMenus = adminStore.genNewMenus;
            for(let key in newMenus){
                let menuObj:RouteRecordRaw = {
                    path:"/" + newMenus[key].name,
                    name:newMenus[key].name,
                    component:()=>import("../pages/homepage/index.vue"),
                    children:[],
                }
                newMenus[key].children.forEach((submenu)=>{
                    menuObj.children?.push({
                        path:submenu.name,
                        name:submenu.name,
                        component:()=>import(`../pages/${newMenus[key].name}/${submenu.name}/index.vue`),
                    });
                });
                // 添加到路由里面
                router.addRoute(menuObj);
            }
            // 动态跳转路由
            router.addRoute({
                path:"/",
                name:"home",
                redirect:"/index",
                component:()=>import("../pages/homepage/index.vue"),
                children:[
                    {
                        path:"index",
                        name:"index",
                        component:()=>import("../pages/index/index.vue"),
                    },
                ],
            });

            return next(to);//下一次进来的路由
        }else{
            localStorage.clear();
            return next("/login")
        }
    }else if(token && to.path==="/login"){
        return next(from); //已经登录，要跳转登录页==>>不跳，保持原来的页面
    }else if(!token && to.path!=="/login"){
        return next("/login");//没有登录，点击去其他页面，要先跳回登录页登录
    }
    else{
        return next();
    }
})

export function initRouter(app:App<Element>){
    app.use(router);
}